<?php

namespace Xrfg\Wallet\TRX\Console;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Xrfg\Core\Trading\Account\Models\Coin;
use Xrfg\Core\Trading\Account\Models\Recharge as RechargeModel;
use Xrfg\Core\Trading\Account\Models\Account;
use Xrfg\Core\Trading\Account\Models\Wtrx;
use Xrfg\Wallet\Common\Jobs\RechargeJob;
use Xrfg\Wallet\TRX\Services\TRXWallet;
use Xrfg\Wallet\TRX\Traits\TRXHelper;

class RechargeTRX extends Command
{
    use TRXHelper;

    protected $signature = 'recharge:trx';

    protected $description = 'TRX 充值';

    protected $times = 0;

    protected $coinId;

    protected $rpc;

    protected $blockNumber;

    public function __construct()
    {
        parent::__construct();

        $this->rpc = new TRXWallet(config('wallet.trx.node.wallet'));
    }

    public function handle()
    {
        if (!$this->coinId) {
            $this->coinId = Coin::where('name', 'TRX')->value('id');
        }

        ++$this->times;
        if ($this->times >= 100) {
            return;
        }
        $this->info('times:'.$this->times);
        $this->blockNumber = Cache::get('TRX:blockNumber', 23114519);
        sleep(1);
        try {
            $result = $this->rpc->getCurrentBlock();
            $blockNumber = $result['block_header']['raw_data']['number'];
            $this->info("latest:{$blockNumber}");
            if ($blockNumber - 1 <= $this->blockNumber) {
                self::handle();

                return;
            }
            $this->info('current:'.$this->blockNumber);
            $this->info('scanning:'.($this->blockNumber + 1));
            $block = $this->rpc->getBlockByNumber($this->blockNumber + 1);
            if (isset($block['transactions'])) {
                $transactions = $block['transactions'];
                // 解析TRX交易
                $this->info('transactions number:'.count($transactions));
                foreach ($transactions as $tx) {
                    if ($tx['ret'][0]['contractRet'] == 'SUCCESS') {
                        if (isset($tx['raw_data']['contract'][0]['parameter']['value']['to_address']) && isset($tx['raw_data']['contract'][0]['parameter']['value']['amount'])) {
                            $hash = $tx['txID'];
                            $address = $tx['raw_data']['contract'][0]['parameter']['value']['to_address']; // 16进制收款地址
                            $number = $tx['raw_data']['contract'][0]['parameter']['value']['amount'] / 1000000;

                            /** @var Wtrx $wtrx */
                            $wtrx = Wtrx::where('hex_address', $address)->first();
                            // 检查地址
                            if ($wtrx) {
                                $isAccountExists = Account::where('coin_id', $this->coinId)
                                    ->where('address', $wtrx->address)
                                    ->exists();
                                if ($isAccountExists) {
                                    $isRechargeExists = RechargeModel::where('hash', $hash)->exists();
                                    // 检查hash
                                    if (!$isRechargeExists) {
                                        RechargeJob::dispatch($this->coinId, $hash, $number, $wtrx->address)
                                            ->onQueue('recharge');
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Cache::forever('TRX:blockNumber', $this->blockNumber + 1);
            self::handle();
        } catch (Exception $exception) {
            Log::error($exception);
            self::handle();
        }
    }
}
